<?php
defined( '_JEXEC' ) or die( 'Restricted Access' );
/**
 * Module GoodRelations
 *
 * @author      Alex Stolz
 * @package     Joomla
 * @subpackage  GoodRelations Module
 * @copyright   Copyright (C) 2012 Alex Stolz, Bundeswehr University Munich - All rights reserved.
 * @license     LGPL
 */
if(!defined("DS"))
    define("DS", DIRECTORY_SEPARATOR);

define("BASE_URI", JURI::base());
define("RDFA_DIR", dirname(__FILE__).DS.'rdfa'.DS);
$shop_uri = JRoute::_(BASE_URI."index.php?option=com_virtuemart");
define("SHOP_URI", $shop_uri );

$lang = VMLANG;//&JFactory::getLanguage();

// request parameters
$option = &JRequest::getWord('option');
$view = &JRequest::getWord('view');
$category_id = &JRequest::getVar('virtuemart_category_id', array());
if (is_array($category_id) && count($category_id) > 0)
    $category_id = $category_id[0];
$product_id = JRequest::getInt('virtuemart_product_id', array());
if (is_array($product_id) && count($product_id) > 0)
    $product_id = $product_id[0];

/** virtuemart **/
if($option == "com_virtuemart"):
    require_once(dirname(__FILE__).DS.'helper.php');
    if (!class_exists( 'VmConfig' ))
        require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'config.php');
    VmConfig::loadConfig();
    
    // media
    if (!class_exists( 'VirtueMartModelMedia' )){
        JLoader::import( 'media', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_virtuemart' . DS . 'models' );
    }
    $model_media = new VirtueMartModelMedia();

    // vendor details
    if (!class_exists( 'VirtueMartModelVendor' )){
        JLoader::import( 'vendor', JPATH_VM_ADMINISTRATOR.DS.'models' );
    }
    $model_vendor = new VirtueMartModelVendor();
    $vendor = $model_vendor->getVendor(); // vendor info also used by products
    
    /** shop main page **/
    if($view == "virtuemart"):
        // company
        $db = JFactory::getDBO();
        $q = "SELECT `file_url`, `file_url_thumb` FROM #__virtuemart_medias ".
            "WHERE `virtuemart_media_id`='".(int)$vendor->virtuemart_media_id[0]."'";
        $db->setQuery($q);
        $image = $db->loadObject();
    
        $company_data = array(
            "maker"=>"urn:goodrelations_shop_extensions:goodrelations-for-joomla:v".$params->get('version'),
            "uri"=>SHOP_URI."#company_data",
            //"addr_id"=>SHOP_URI."#address_vendor_".$vendor->virtuemart_vendor_id,
            "company_name"=>strip_tags_enhanced($vendor->vendor_store_name),
            "language"=>$lang,
            //"country"=>$vendor->vendor_country,
            //"city"=>$vendor->vendor_city,
            //"zip"=>$vendor->vendor_zip,
            //"street"=>$vendor->vendor_address_1,
            "phone"=>$vendor->vendor_phone,
            "logo_uri"=>($image->file_url?BASE_URI.$image->file_url:$image->file_url_thumb?BASE_URI.$image->file_url_thumb:""),
            "page"=>$vendor->vendor_url?$vendor->vendor_url:BASE_URI
        );
        createRDFaSnippet("company", $company_data);
        
        // vendors
        $vendors = $model_vendor->getVendors();
        $stores = array();
        foreach ($vendors as $vendor) {
            // get image
            $db = JFactory::getDBO();
            $q = "SELECT `file_url`, `file_url_thumb` FROM #__virtuemart_medias ".
                "WHERE `virtuemart_media_id`='".(int)$vendor->virtuemart_media_id[0]."'";
            $db->setQuery($q);
            $image = $db->loadObject();
    
            $vendor_data = array(
                "id"=>SHOP_URI."#vendor_".$vendor->virtuemart_vendor_id,
                //"addr_id"=>SHOP_URI."#address_vendor_".$vendor->virtuemart_vendor_id,
                "name"=>strip_tags_enhanced($vendor->vendor_store_name),
                "description"=>strip_tags_enhanced($vendor->vendor_store_desc),
                "language"=>$lang,
                //"country"=>$vendor->vendor_country,
                //"city"=>$vendor->vendor_city,
                //"zip"=>$vendor->vendor_zip,
                //"street"=>$vendor->vendor_address_1,
                "phone"=>$vendor->vendor_phone,
                "logo_uri"=>($image->file_url?BASE_URI.$image->file_url:$image->file_url_thumb?BASE_URI.$image->file_url_thumb:""),
                "page"=>$vendor->vendor_url?$vendor->vendor_url:BASE_URI
            );
            $stores[] = $vendor_data;
        }
        createRDFaSnippet("vendor", array("company_uri"=>SHOP_URI."#company_data", "stores"=>$stores));
        
        // manufacturers
        if (!class_exists( 'VirtueMartModelManufacturer' )){
            JLoader::import( 'manufacturer', JPATH_VM_ADMINISTRATOR.DS.'models' );
        }
        $model_manufacturer = new VirtueMartModelManufacturer();
        $manufacturers = $model_manufacturer->getManufacturers();
        
        $manufactuer_data = array();
        foreach ($manufacturers as $manufacturer) {
            $manufactuer_data[] = array(
                "name"=>SHOP_URI."#manufacturer_".$manufacturer->virtuemart_manufacturer_id,
                "company_name"=>strip_tags_enhanced($manufacturer->mf_name),
                "uri"=>$manufacturer->mf_url,
                "language"=>$lang
            );
        }
        createRDFaSnippet("manufacturers", $manufactuer_data);
        
        // categories
        if (!class_exists( 'VirtueMartModelCategory' )){
            JLoader::import( 'manufacturer', JPATH_VM_ADMINISTRATOR.DS.'models' );
        }
        $model_category = new VirtueMartModelCategory();
        $categories = $model_category->getCategoryTree();
        
        $category_data = array();
        foreach ($categories as $category) {
            $category_data[] = array(
                "id"=>$category->virtuemart_category_id,
                "uri"=>SHOP_URI."#category_".$category->virtuemart_category_id,
                "name"=>strip_tags_enhanced($category->category_name),
                "description"=>strip_tags_enhanced($category->category_description),
                "parent_id"=>$category->category_parent_id,
                "parent"=>SHOP_URI."#category_".$category->category_parent_id
            );
        }
        createRDFaSnippet("categories", $category_data);
        

    /** product detail page **/
    elseif($view == "productdetails"):
        // product details
        if (!class_exists( 'VirtueMartModelProduct' )){
            JLoader::import( 'product', JPATH_VM_ADMINISTRATOR.DS.'models' );
        }
        $model_product = new VirtueMartModelProduct();
        $product = $model_product->getProductSingle($product_id, false);
        // $parent = $product->product_parent_id;
        // $children = $model_product->getProductChilds($product_id);

        // product media
        $product_media = $model_media->getFiles(true, false, $product_id, null, array("file_is_product_image = '1'"), false);
        $product_images = array();
        $product_thumbs = array();
        foreach($product_media as $product_medium) {
            if ($product_medium->file_url)
                $product_images[] = BASE_URI.$product_medium->file_url;
            if ($product_medium->file_url_thumb)
                $product_thumbs[] = BASE_URI.$product_medium->file_url_thumb;
        }

        // currency
        if (empty($product->product_currency))
            $product->product_currency = $vendor->vendor_currency; // fallback

		$elements = array(
			'BusinessEntityType',
			'DeliveryMethod',
			'PaymentMethod',
			'WarrantyScope'
		);
		
		foreach($elements as $search) {
			$parameter_array_name = strtolower(preg_replace('/^_/', '', preg_replace('/[A-Z]/','_\\0',$search)));
			$$parameter_array_name = getAllParametersForElement($search, $params); // get parameters from backend
		}

		// offering details got from master data in the backend
		$prop = array();
		$namespaces = array();
		$namespaces['gr'] = "http://purl.org/goodrelations/v1#";
		foreach($elements as $element) {

			$property = NULL;
			$parameter_array_name = strtolower(preg_replace('/^_/', '', preg_replace('/[A-Z]/','_\\0',$element)));

			switch($element) {
				case 'BusinessEntityType':
					$property = 'customer_types';
				break;
				case 'DeliveryMethod':
					$property = 'delivery_options';
				break;
				case 'PaymentMethod':
					$property = 'payment_methods';
				break;
				case 'WarrantyScope':
					$property = 'warranty_promises';
				break;
			}

			if($$parameter_array_name != NULL && $property != NULL) {
				if($element == 'WarrantyScope') {
					$iter_arr = array();
					foreach($$parameter_array_name as $key => $value) {
						$warranty = array();
						$warranty['uri'] = SHOP_URI."#warrantypromise_${key}_${value}";
						$warranty['scope'] = $namespaces['gr'].$key;
						$warranty['duration'] = max($value, 0);
						$iter_arr[] = $warranty;
					}
					$prop[$property] = $iter_arr;
				}
				else {
					$iter_arr = array();
					foreach($$parameter_array_name as $key => $value) {
						$iter_arr[] = $namespaces['gr'].$key;
					}
					$prop[$property] = $iter_arr;
				}
			}
		}

		// business function
		if(($business_function = $params->get('BusinessFunction')) != NULL) {
			$prop["business_function"] = $namespaces['gr'].$business_function;
		}

        // eligible regions
        $regions_array = array();
		if(($eligible_regions = $params->get('eligibleRegions')) != NULL) {
			$regions_array = explode(',', $eligible_regions);
			if(sizeof($regions_array)>0)
			foreach($regions_array as $key=>$value) {
				$regions_array[$key] = trim($value);
			}
		}
		$prop["eligible_regions"] = $regions_array;
		
		// features
		$features = array();
		$object_properties = array("Weight", "Length", "Width", "Height");
		foreach ($object_properties as $item) {
			$name = strtolower($item);
			$oprop = array();
			$oprop['type'] = "quantitative";
			$oprop['datatype'] = "float";
			if($name=="length")
				$oprop['uri'] = "gr:depth";
			else
				$oprop['uri'] = "gr:".$name;
			$oprop['unit_code'] = $item=="Weight"?$product->product_weight_uom:$product->product_lwh_uom;
			$oprop['value'] = number_format($product->{"product_".$name}, 2, ".", "");
			$oprop['name'] = $name;
			if($oprop['value']>0)
				$features[] = $oprop;
		}
		$prop['features'] = $features;
		
		// calculate price and currency
		$prices = $model_product->getPrice($product, array(), 1);
    	
    	if (!class_exists('CurrencyDisplay')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php');
		$currencyDisplay = CurrencyDisplay::getInstance();
		$product->product_price = $currencyDisplay->convertCurrencyTo((int)$currencyDisplay->getCurrencyForDisplay(), $prices["salesPrice"]);
		
		if (!class_exists( 'VirtueMartModelCurrency' )){
            JLoader::import( 'currency', JPATH_VM_ADMINISTRATOR.DS.'models' );
        }
        $model_currency = new VirtueMartModelCurrency();
        $product->product_currency = $model_currency->getCurrency($currencyDisplay->getCurrencyForDisplay())->currency_code_3;

        // create RDFa snippets
        createRDFaSnippet("product", array_merge($prop, array(
            "maker"=>"urn:goodrelations_shop_extensions:goodrelations-for-joomla:v".$params->get('version'),
            "product_name"=>strip_tags_enhanced($product->product_name),
            "category_uri"=>"self:category_".$category_id,
            "product_short"=>strip_tags_enhanced($product->product_s_desc),
            "product_long"=>strip_tags_enhanced($product->product_desc),
            "language"=>$lang,
            "company_uri"=>SHOP_URI."#company_data",
            "stock_level"=>number_format(max($product->product_in_stock, 0), 2, ".", ""),
            "stock_unit"=>"C62",
            "product_type"=>($params->get('offer_individuals')?"gr:Individual":"gr:SomeItems"),
            "product_uri"=>$product->product_url,
            "valid_from"=>w3cdate(time()), //$product->product_available_date,
            "valid_through"=>$params->get('offering_validity')?w3cdate(time(), $params->get('offering_validity')):0, //$product->product_available_date, // TODO
            "product_image_uris"=>$product_images,
            "product_thumbnail_uris"=>$product_thumbs,
            "sku"=>$product->product_sku,
            "manufacturer_uri"=>SHOP_URI."#manufactuer_".$product->virtuemart_manufacturer_id,
            "vat"=>VmConfig::get('show_tax')?"true":"false",
            "weight"=>$product->product_weight,
            "width"=>$product->product_width,
            "length"=>$product->product_length,
            "height"=>$product->product_height,
            "prefixes"=>array(array("ns_prefix"=>"self", "ns_uri"=>SHOP_URI."#")),
            "uom"=>array("weight"=>$product->product_weight_uom, "lwh"=>$product->product_lwh_uom),
            "price"=>VmConfig::get('show_prices', 1)?number_format(max($product->product_price, 0), 2, ".", ""):0,
            "currency"=>$product->product_currency,
            "price_quantity_start"=>max($product->product_price_quantity_start, 0),
            "price_quantity_end"=>max($product->product_price_quantity_end, 0),
        )));
        
        // product ratings
        $ratings_snippet_output = false;   
        if(VmConfig::get('showRatingFor') == "all") {
            if (!class_exists( 'VirtueMartModelRatings' )){
                JLoader::import( 'ratings', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_virtuemart' . DS . 'models' );
            }
            $model_ratings = new VirtueMartModelRatings();
            $rating = $model_ratings->getRatingByProduct($product_id);
            
            if($rating->published) {
                createRDFaSnippet("review", array(
                    "rating"=>$rating->rating,
                    "votes"=>$rating->ratingcount,
                    "product_uri"=>$product->link,
                    "product_id"=>$product_id
                ));
                $ratings_snippet_output = true; 
            }
        }
        if(!$ratings_snippet_output)
            echo "	</div>
</div>\n";
        
    endif;
    
    
    // $document = &JFactory::getDocument();
    // $document->setMetaData('content-type', "application/xhtml+xml", true);
	if(!$params->get('configuration_done')) { //!file_exists(dirname(__FILE__).DS.'mod_goodrelations.xml') || !$configuration_done) {
		require_once(dirname(__FILE__).DS.'create_manifest.php');
		echo "<div><b>Settings file for Semantic SEO module was updated. Check out additional configuration options in the back-end. This message will disappear automatically once you visited the back-end and saved the new module settings.</b></div>";
		//vmdebug('Install file for GoodRelations module was updated. Please check out the new options of the extension in the backend and if necessary confirm to finish the configuration!');
		
		// ping semantic web search engines
		if(strpos($params->get('ping_submission_base_uri'), JURI::base()) === false) {
		    notifySWSE($params, BASE_URI."sitemap.xml");
		}
	}

    require_once(JModuleHelper::getLayoutPath('mod_goodrelations'));
endif;

?>
